package org.feng.support.impl;

import cn.hutool.core.io.file.FileNameUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.feng.entity.PubResource;
import org.feng.entity.result.UploadResult;
import org.feng.support.UploadInterface;
import org.feng.support.proxy.ProxyUpload;
import org.feng.utils.UploadFileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * oss
 *
 * @author : FengShuai
 * @since : 2024/6/27 9:24
 */
public class AliOss implements UploadInterface {

    private OSS ossClient;
    private PubResource pubResource;

    public AliOss(PubResource pubResource) {
        this.pubResource = pubResource;
        this.ossClient = new OSSClientBuilder().build(pubResource.getEndpoint().trim(), pubResource.getKey().trim(), pubResource.getSecret().trim());
    }

    @Override
    public UploadResult putFile(MultipartFile file) {
        UploadResult uploadResult = ProxyUpload.checkMd5(file);
        if (uploadResult.getFileUrl() != null) {
            return uploadResult;
        }
        String filename = UploadFileUtils.getFileName(file.getOriginalFilename());
        try {
            ossClient.putObject(pubResource.getBucket(), filename, file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        uploadResult = new UploadResult();
        uploadResult.setFileName(file.getOriginalFilename());
        uploadResult.setFileUrl(getFileLink(filename));
        uploadResult.setFileSize(file.getSize());
        uploadResult.setFileType(FileNameUtil.extName(file.getOriginalFilename()));
        uploadResult.setFileMd5(uploadResult.getFileMd5());
        ProxyUpload.saveMd5(uploadResult);
        return uploadResult;
    }

    private String getFileLink(String fileName) {
        String url = "";
        if (this.pubResource.getEndpoint().contains("https://")) {
            url = this.pubResource.getEndpoint().replace("https://", "https://" + this.pubResource.getBucket() + ".");
        }
        if (this.pubResource.getEndpoint().contains("http://")) {
            url = this.pubResource.getEndpoint().replace("http://", "http://" + this.pubResource.getBucket() + ".");
        }
        return url + "/" + fileName;
    }
}
